package com.bluedot.www.core.service;


import com.bluedot.www.core.pojo.DO.CharacterReport;
import com.bluedot.www.core.pojo.DO.Customer;
import com.bluedot.www.core.pojo.DO.User;
import com.bluedot.www.core.pojo.DTO.CustomerDTO;
import com.bluedot.www.core.pojo.DTO.ExportUserDTO;
import com.bluedot.www.core.pojo.DTO.UserDTO;
import com.bluedot.www.core.utils.DbUtil;
import com.bluedot.www.core.utils.ExcelUtils;
import com.bluedot.www.framework.mvc.servlet.http.MultipartFile;
import com.bluedot.www.framework.mvc.servlet.http.ResponseEntity;
import com.bluedot.www.framework.mvc.utils.Assert;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * 导出工具类，包括所有的导出功能
 *
 * @author He Peng
 * @version 1.0
 * @date 2021/8/8 8:28
 */
public class ExportService {

    public static Object execute(String methodName, Object[] param) throws IOException, FileUploadException {
        ExportService exportService = new ExportService();
        Object result = null;
        switch (methodName) {
            case "exportCustomerInfo":
                result = exportService.exportCustomerInfo((List<Long>) param[0]);
                break;
            case "importCustomerInfo":
                result = exportService.importCustomerInfo((MultipartFile) param[0],(HttpServletRequest) param[1]);
                break;
            case "exportCharacterReport":
                result = exportService.exportCharacterReport((List<Long>) param[0], (HttpServletResponse) param[1]);
                break;
            case "exportFeature":
                result = exportService.exportFeature((List<Long>) param[0], (HttpServletResponse) param[1]);
                break;
            case "exportHandwritingImg":
                result = exportService.exportHandwritingImg((List<Long>) param[0], (HttpServletResponse) param[1]);
                break;
            case "exportUserInfo":
                result = exportService.exportUserInfo((List<Long>) param[0]);
                break;
            case "testExportUserInfo":
                result = exportService.testExportUserInfo();
                break;
            default:
                throw new RuntimeException("Method NOT FOUND, method name: " + methodName);
        }
        return result;
    }

    /**
     * <p>根据客户编号导出客户信息</p>
     * 注意：客户编号可以一个也可以多个
     *
     * @param customerIds : 客户编号
     * @return boolean
     * @author Deng HongWei
     * @date 2021/8/8 14:00
     */
    private ResponseEntity exportCustomerInfo(List<Long> customerIds) {
        InputStream in;
        try {
            List<CustomerDTO> lists = new ArrayList<>();
            //根据id集合查客户DTO数据集合
            for (Long customerId : customerIds) {

                CustomerDTO customerDTO = (CustomerDTO) CustomerService.execute("findById", new Object[]{customerId});
                Assert.notNull(customerDTO, "未查询到相应客户，导致导出信息失败");
                lists.add(customerDTO);
            }
            //下面做数据处理,先设置文件返回类型
            in = ExcelUtils.customerDTOToExcel(lists, new ByteArrayOutputStream());
            return new ResponseEntity("客户信息.xlsx", in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * <p>根据客户编号导出客户信息</p>
     *
     * @param file : 传入的excel文件
     * @return boolean
     * @author Deng HongWei
     * @date 2021/8/8 14:00
     */
    private boolean importCustomerInfo(MultipartFile file, HttpServletRequest req) {
        try {
            List<CustomerDTO> customerDTOS = ExcelUtils.excelToCustomerDTO(file.getInputStream());
            for (CustomerDTO customerDTO : customerDTOS) {
                Customer customer = customerDTO.getCustomer();
                //这两句代码等真正走的时候再打开
//                UserDTO UserDTO = (UserDTO)req.getSession(false).getAttribute("SESSION_KEY_USER");
//                customer.setUserId(UserDTO.getUser().getId());
                //假设userId为这样
                customer.setUserId(DbUtil.generateId());
                //客户是否存在未分析的记录，导入进来肯定为0：没有
                customer.setStatus(0);
                if (customer.getGroupId() == null){
                    //默认分组id为1L，可改，反正是自己设定的默认分组
                    customer.setGroupId(1L);
                }
                Long flag1 = (Long) CustomerService.execute("insertCustomer", new Object[]{customer});
                boolean flag2 = (boolean) FamilyNumberService.execute("insertFamilyNumbers", new Object[]{customerDTO.getFamilyNumbers(), flag1});
                if (flag1 == null | !flag2) {
                    //如果有一个不满足条件则返回错误，文件导入失败
                    return false;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * <p>根据报告编号导出性格报告</p>
     *
     * @param reportIds : 性格报告编号
     * @return boolean
     * @author Deng HongWei
     * @date 2021/8/8 14:02
     */
    private boolean exportCharacterReport(List<Long> reportIds, HttpServletResponse response) throws IOException, FileUploadException {

        for (Long reportId : reportIds) {
            CharacterReport characterReport = (CharacterReport) CharacterReportService.execute("queryReportDetails", new Object[]{reportId});
            if (characterReport.getUserId() == 0) {
                return exportUserReport(reportIds, response);
            } else if (characterReport.getCustomerId() == 0) {
                return exportCustomerReport(reportIds, response);
            }

        }
      /*  for (int i = 0; i < reportIds.size(); i++) {
            CharacterReport characterReport = null;
            String reportName = null;
            boolean flag = false;
            try {
                characterReport = (CharacterReport) Service.doService("CharacterReportService", "queryReportDetails", new Object[]{reportIds.get(i)});
                if (characterReport.getUserId() != null){
                    User user= (User) Service.doService("UserService", "findUserByUserId", new Object[]{characterReport.getUserId()});
                    reportName = user.getName();
                    listUrl.add(characterReport.getReportLink());
                    listFileName.add(reportName);
                }else if(characterReport.getCustomerId() != null){
                    CustomerDTO customerDTO= (CustomerDTO) Service.doService("CustomerService", "findById", new Object[]{characterReport.getCustomerId()});
                    reportName = customerDTO.getCustomer().getName()+".docx";
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }*/
//        ExcelUtils.exportToZip(listUrl,"性格报告",fileNames,response)
        return false;
    }

    /**
     * @param reportIds
     * @param response
     * @return boolean
     * @author Deng HongWei
     * @date 2021/9/10 15:44
     */
    private boolean exportUserReport(List<Long> reportIds, HttpServletResponse response) throws IOException, FileUploadException {
        ArrayList<String> listUrl = new ArrayList<>();
        ArrayList<String> listName = new ArrayList<>();
        for (Long reportId : reportIds) {
            CharacterReport characterReport = (CharacterReport) CharacterReportService.execute("queryReportDetails", new Object[]{reportId});
            User user = (User) UserService.execute("findUserByUserId", new Object[]{characterReport.getUserId()});
            listUrl.add(characterReport.getReportLink());
            listName.add(user.getName() + ".docx");
        }
        return ExcelUtils.exportToZip(listUrl, "性格报告", listName, response);
    }


    private boolean exportCustomerReport(List<Long> reportIds, HttpServletResponse response) {
        return true;
    }

    /**
     * 根据性格报告编号导出特征
     *
     * @param reportIds : 性格报告编号
     * @return boolean
     * @author He Peng
     * @date 2021/8/8 14:04
     */
    private boolean exportFeature(List<Long> reportIds, HttpServletResponse response) {
        return true;
    }

    /**
     * 根据性格报告编号导出笔迹图片
     *
     * @param reportIds : 性格报告编号
     * @return boolean
     * @author He Peng
     * @date 2021/8/8 14:09
     */
    private boolean exportHandwritingImg(List<Long> reportIds, HttpServletResponse response) {
        return true;
    }

    /**
     * 根据用户编号导出用户信息
     *
     * @param userIds :
     * @return boolean
     * @author He Peng
     * @date 2021/8/8 14:10
     */
    private ResponseEntity exportUserInfo(List<Long> userIds) {
        List<User> users = (List<User>) UserService.execute("queryUsersByUserId", new Object[]{userIds});
        //        System.out.println(users.get(0));
        /*
        查出来的数据
        User{id=1, account=abc12, phoneNum=1, password=12345678, usertype=0,
        gender=1, email=197011281712@qq.com, portrait=1, birthday=2021-08-31, name=张山,
        status=0, isDeleted=0, interest=兴趣篮球, professional=码农,
        gmtCreate=2021-09-01 23:29:09.0, gmtModified=2021-09-01 23:29:09.0,
        lastLogin=2021-08-25 16:17:15.0}

        不需要导出的数据
        id,portrait,isDeleted,password

        */
        List<ExportUserDTO> userDTOS = new ArrayList<>();
        for (User user : users) {
            ExportUserDTO userDTO = new ExportUserDTO();
            userDTO.setAccount(user.getAccount());
            userDTO.setPhoneNum(user.getPhoneNum());
            if (user.getUsertype() == 1) {
                userDTO.setUsertype("心理咨询师");
            } else {
                userDTO.setUsertype("普通用户");
            }
            if (user.getGender() == 1) {
                userDTO.setGender("女");
            } else {
                userDTO.setGender("男");
            }
            userDTO.setEmail(user.getEmail());
            userDTO.setBirthday(user.getBirthday());
            userDTO.setName(user.getName());
            if (user.getStatus() == 1) {
                userDTO.setStatus("被封禁");
            } else {
                userDTO.setStatus("正常");
            }
            userDTO.setInterest(user.getInterest());
            userDTO.setProfessional(user.getProfessional());
            userDTO.setGmtCreate(user.getGmtCreate());
            userDTO.setGmtModified(user.getGmtModified());
            userDTO.setLastLogin(user.getLastLogin());
            userDTOS.add(userDTO);
        }
        System.out.println("================================================");
        for (ExportUserDTO userDTO : userDTOS) {
            System.out.println(userDTO);
        }

        XSSFWorkbook workbook = ExcelUtils.getWorkbook(userDTOS,
                new String[]{"account", "phoneNum", "usertype", "gender", "email", "birthday", "name", "status", "interest", "professional", "gmtCreate", "gmtModified", "lastLogin"},
                new String[]{"账户名", "手机号", "用户类型", "性别", "邮箱", "生日", "用户姓名", "用户状态", "兴趣爱好", "职业", "创建时间", "修改时间", "最后一次登录时间"});
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            workbook.write(os);
            byte[] bytes = os.toByteArray();
            return new ResponseEntity("用户信息表格.xlsx", bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private ResponseEntity testExportUserInfo() {
        List<ExportUserDTO> userDTOS = new ArrayList<>();
        for (int i = 1; i < 5; i++) {
            ExportUserDTO userDTO = new ExportUserDTO();
            userDTO.setAccount("abc" + i);
            userDTO.setPhoneNum("phone" + i);
            if (i % 2 == 0) {
                userDTO.setUsertype("心理咨询师");
            } else {
                userDTO.setUsertype("普通用户");
            }

            if (i % 2 == 0) {
                userDTO.setGender("女");
            } else {
                userDTO.setGender("男");
            }
            userDTO.setEmail("email" + i);
            userDTO.setBirthday(new Date(123456));
            userDTO.setName("name" + i);
            if (i % 2 == 0) {
                userDTO.setStatus("被封禁");
            } else {
                userDTO.setStatus("正常");
            }
            userDTO.setInterest("interest" + i);
            userDTO.setProfessional("Professional" + i);
            userDTO.setGmtCreate(new Timestamp(135465456));
            userDTO.setGmtModified(new Timestamp(135465456));
            userDTO.setLastLogin(new Timestamp(135465456));
            userDTOS.add(userDTO);
        }

        /*System.out.println("================================================");
        for (ExportUserDTO userDTO : userDTOS) {
            System.out.println(userDTO);
        }*/

        XSSFWorkbook workbook = ExcelUtils.getWorkbook(userDTOS,
                new String[]{"account", "phoneNum", "usertype", "gender", "email", "birthday", "name", "status", "interest", "professional", "gmtCreate", "gmtModified", "lastLogin"},
                new String[]{"账户名", "手机号", "用户类型", "性别", "邮箱", "生日", "用户姓名", "用户状态", "兴趣爱好", "职业", "创建时间", "修改时间", "最后一次登录时间"});
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            workbook.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = os.toByteArray();
        try {
            return new ResponseEntity("用户信息表格.xlsx", bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
